<template>
  <div class="system-user-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="600">
      <CommonUpload ref="uploadRef" list-type="picture" :file-list="state.list" accped=".jpg,.jpeg,.png" multiple>
        <el-button type="primary">选择照片</el-button>
        <template #tip>
          <div class="el-upload__tip">只支持jpg、jpg图片，大小50MB以内</div>
        </template>
      </CommonUpload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSubmit" size="default" :loading="state.submit.loading"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="uploadPhoto">
import { reactive, ref } from 'vue';
import { addPhoto } from '/@/api/activity'
import { DialogType } from '/@/constants/dialog-type';
import { createMachineType, updateMachineType } from '/@/api/machine-type';
import { ElMessage } from 'element-plus';
import CommonUpload from '/@/components/common-upload/index.vue';
import { useRoute } from 'vue-router'

const route = useRoute()

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

const uploadRef = ref();

const state = reactive({
  id: '',
  list: [],
  submit: {
    loading: false
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: '上传照片'
  }
});

// 打开弹窗
const openDialog = (type: string) => {
  state.dialog.type = type;
  state.dialog.isShowDialog = true;
  state.dialog.title = `上传照片`;
};

// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
  closeDialog();
};

// 提交
const onSubmit = async () => {
  try {
    state.submit.loading = true;
    const files = uploadRef.value.normalizeFileList()

    if (files.length === 0) {
      ElMessage.warning('请先上传照片');
      return
    }

    await addPhoto(route.query.activity_id as string, { photoes: files })
    ElMessage.success('保存成功');
    closeDialog();
    emit('refresh');
  } catch (err) {
    console.log(err);
  }

  state.submit.loading = false;
};

// 暴露变量
defineExpose({
  openDialog,
  closeDialog
});
</script>
